package com.mh.common;

import com.mh.dto.bo.UserManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Date:2024/11/14
 * author:zmh
 * description: WebSocket处理器
 **/

@Component
@RequiredArgsConstructor
@Slf4j
public class RtcWebSocketHandler  extends TextWebSocketHandler {

    // 管理用户的加入和退出...
    private final UserManager userManager;

    // 用户连接成功
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 取出用户ID，存储
        String query = session.getUri().getQuery();
        String userId = null;
        String roomId = null;
        // 提取 token 参数
        if (query != null) {
            String[] params = query.split("&");
            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2 && "roomId".equals(keyValue[0])) {
                    roomId = keyValue[1];
                }
                if (keyValue.length == 2 && "userId".equals(keyValue[0])) {
                    userId = keyValue[1];
                }
            }
        }

        // 将用户保存
        userManager.addUser(roomId, userId, session);
        // 广播join消息
        userManager.sendMessageAllUser();
    }


    // 接收到客户端消息，解析消息内容进行分发
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 转换并分发消息
        log.info("收到消息");
    }

    // 处理断开的连接
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("用户退出房间");
        userManager.removeRoom(session);
    }
}
